/**
 * 
 */
package qy.jalgotrade.utils;

import java.util.ArrayList;
import java.util.List;

import qy.jalgotrade.utils.PySpecs;

/**
 * I'm not using collections.deque because:<br />
 * 1: Random access is slower.<br />
 * 2: Slicing is not supported.
 * 
 * @author qy
 *
 */
public class ListDeque<T> implements PySpecs.SeqGetItem<T> {

	private ArrayList<T> __values;

	private int __maxLen;

	/**
	 * 
	 * @param maxLen
	 */
	public ListDeque(int maxLen) {

		assert maxLen > 0 : "Invalid maximum length";
		__maxLen = maxLen;
		__values = new ArrayList<>();
	}

	/**
	 * 
	 * @return
	 */
	public int getMaxLen() {

		return __maxLen;
	}

	/**
	 * 
	 * @param value
	 */
	public void append(T value) {

		__values.add(value);
		// Check bounds
		if (__values.size() > __maxLen) {
			__values.remove(0);
		}
	}

	/**
	 * 
	 * @return
	 */
	public List<T> data() {

		return __values;
	}

	/**
	 * 
	 * @param maxLen
	 */
	public void resize(int maxLen) {

		assert maxLen > 0 : "Invalid maximum length";

		int startIdx = __values.size() - maxLen;
		if (startIdx > 0) {
			ArrayList<T> values = new ArrayList<>(maxLen);
			values.addAll(startIdx, __values);
			__values = values;
		}
		__maxLen = maxLen;
	}

	/*
	 * (non-Javadoc)
	 * @see qy.jalgotrade.utils.PySpecs.Len#__len__()
	 */
	@Override
	public int __len__() {

		return __values.size();
	}

	/*
	 * (non-Javadoc)
	 * @see qy.jalgotrade.utils.PySpecs.SeqGetItem#__getitem__(int)
	 */
	@Override
	public T __getitem__(int idx) {

		if (idx < 0) {
			idx += __len__();
		}
		return __values.get(idx);
	}
	
	@Override
	public String toString() {

		return __values.toString();
	}
}
